package com.kly.user.task.v2;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.chatterService.ChatService;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.UserChatterMappingEntity;
import com.kly.user.db.entity.UserDailyActivityEntity;
import com.kly.user.db.entity.UserMsgEntity;
import com.kly.user.dto.chatter.request.ConversationReq;
import com.kly.user.enums.AppEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 会话列表修复任务
 */
@Service
public class RepairChatListTask {

    private static Log logger = LogFactory.getLog(RepairChatListTask.class);

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    @NacosValue(value = "${enable.repair.switch:true}", autoRefreshed = true)
    private Boolean enableFlashChatSwitch;
    private String localIP = NetUtil.getLocalhostStr();
    @Resource
    UserMsgDao userMsgDao;
    @Resource
    ChatService chatService;
    @Resource
    UserChatterMappingDao userChatterMappingDao;
    @Resource
    UserMsgUnreadNumDao userMsgUnreadNumDao;

    /**
     * 执行频率：10分钟
     */
    @Scheduled(fixedDelay = 1000 * 600)
    public void run() {
        logger.info("====RepairChatListTask start");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============RepairChatListTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!enableFlashChatSwitch) {
            logger.info("=============RepairChatListTask, enableFlashchatSwitch:{}", enableFlashChatSwitch);
            return;
        }

        // 会话数据修复
        repairChatList();
        // 清除无效用户的未读消息数
        userMsgUnreadNumDao.clearAllUnreadMessageForInvalidAccount();

    }

    /**
     * 会话数据修复
     */
    private void repairChatList() {
        final List<UserMsgEntity> userMsgEntities = userMsgDao.listTodayMessageWithoutSession();
        if (CollectionUtils.isEmpty(userMsgEntities)) {
            return;
        }

        for (UserMsgEntity entity : userMsgEntities) {

            final ConversationReq conversationReq = ConversationReq.builder().latestMsg(entity.getContent()).latestTime(entity.getGmtCreate()).source(AppEnum.MEBOO.getAppCode()).type(1).fromUserCode(entity.getFromUserCode()).toUserCode(entity.getToUserCode()).build();

            final List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.queryByModelUserCode(entity.getToUserCode());
            if (CollectionUtils.isNotEmpty(userChatterMappingEntities)) {
                conversationReq.setChatterUserCode(userChatterMappingEntities.get(0).getChatterUserCode());
            }

            chatService.storageConversation(conversationReq);
        }
    }

}